﻿//-----------------------------------------------------------------------
// <Copyright>
// * Copyright (C) 2022 RuYiAdmin All Rights Reserved
// </Copyright>
//-----------------------------------------------------------------------

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using RuYiAdmin.Net.CommonInfrastructure.Classes;
using RuYiAdmin.Net.CommonInfrastructure.Configurations;
using RuYiAdmin.Net.CommonInfrastructure.Constants.System;
using RuYiAdmin.Net.CommonInfrastructure.Exceptions.Framework;
using RuYiAdmin.Net.ServiceLayer.BusinessService.Interface.SystemInterface;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace RuYiAdmin.Net.WebApi.RuYiAdminCode.RuYiAdminUtility
{
    public class RuYiAdminApplication
    {
        #region 启动业务作业

        /// <summary>
        /// 启动业务作业
        /// </summary>
        /// <returns></returns>
        public static async Task StartScheduleJobAsync(IApplicationBuilder app)
        {
            await app.ApplicationServices.GetService<ISysScheduleJobService>().StartScheduleJobAsync();
        }

        #endregion

        #region 加载系统缓存

        /// <summary>
        /// 加载系统缓存
        /// </summary>
        /// <returns></returns>
        public static async Task LoadSystemCache(IApplicationBuilder app)
        {
            //加载机构缓存
            await app.ApplicationServices.GetService<ISysOrganizationService>().LoadSystemOrgCache();

            //加载用户缓存
            await app.ApplicationServices.GetService<ISysUserService>().LoadSystemUserCache();

            //加载菜单缓存
            await app.ApplicationServices.GetService<ISysMenuService>().LoadSystemMenuCache();

            //加载菜单与多语缓存
            await app.ApplicationServices.GetService<ISysMenuLanguageService>().LoadSystemMenuLanguageCache();

            //加载角色缓存
            await app.ApplicationServices.GetService<ISysRoleService>().LoadSystemRoleCache();

            //加载角色与菜单缓存
            await app.ApplicationServices.GetService<ISysRoleMenuService>().LoadSystemRoleMenuCache();

            //加载角色与机构缓存
            await app.ApplicationServices.GetService<ISysRoleOrgService>().LoadSystemRoleOrgCache();

            //加载角色与用户缓存
            await app.ApplicationServices.GetService<ISysRoleUserService>().LoadSystemRoleUserCache();

            //加载数据字典缓存
            await app.ApplicationServices.GetService<ISysCodeTableService>().LoadSystemCodeTableCache();

            //加载多语缓存
            await app.ApplicationServices.GetService<ISysLanguageService>().LoadSystemLanguageCache();

            //加载计划任务缓存
            await app.ApplicationServices.GetService<ISysScheduleJobService>().LoadBusinessScheduleJobCache();

            //加载行政区域缓存
            await app.ApplicationServices.GetService<ISysAreaService>().LoadSysAreaCache();
        }

        #endregion

        #region 清理系统缓存

        /// <summary>
        /// 清理系统缓存
        /// </summary>
        /// <returns></returns>
        public static async Task ClearSystemCache(IApplicationBuilder app)
        {
            //清理机构缓存
            await app.ApplicationServices.GetService<ISysOrganizationService>().ClearSystemOrgCache();

            //清理用户缓存
            await app.ApplicationServices.GetService<ISysUserService>().ClearSystemUserCache();

            //清理菜单缓存
            await app.ApplicationServices.GetService<ISysMenuService>().ClearSystemMenuCache();

            //清理菜单与多语缓存
            await app.ApplicationServices.GetService<ISysMenuLanguageService>().ClearSystemMenuLanguageCache();

            //清理角色缓存
            await app.ApplicationServices.GetService<ISysRoleService>().ClearSystemRoleCache();

            //清理角色与菜单缓存
            await app.ApplicationServices.GetService<ISysRoleMenuService>().ClearSystemRoleMenuCache();

            //清理角色与机构缓存
            await app.ApplicationServices.GetService<ISysRoleOrgService>().ClearSystemRoleOrgCache();

            //清理角色与用户缓存
            await app.ApplicationServices.GetService<ISysRoleUserService>().ClearSystemRoleUserCache();

            //清理数据字典缓存
            await app.ApplicationServices.GetService<ISysCodeTableService>().ClearSystemCodeTableCache();

            //清理多语缓存
            await app.ApplicationServices.GetService<ISysLanguageService>().ClearSystemLanguageCache();

            //清理计划任务缓存
            await app.ApplicationServices.GetService<ISysScheduleJobService>().ClearBusinessScheduleJobCache();

            //清理行政区域缓存
            await app.ApplicationServices.GetService<ISysAreaService>().ClearSysAreaCache();
        }

        #endregion

        #region 自动构建数据库

        /// <summary>
        /// 自动构建数据库
        /// </summary>
        /// <returns></returns>
        public static async Task BuildDatabase()
        {
            await Task.Run(async () =>
            {
                var dbType = RuYiGlobalConfig.DBConfig.DBType;
                if (dbType > 4 && dbType != 10)
                {
                    throw new RuYiAdminCustomException(ExceptionMessage.DatabaseNotSupportedExceptionMessage);
                }

                if (RuYiGlobalConfig.DBConfig.AutomaticallyBuildDatabase)
                {
                    try
                    {
                        RuYiAdminDbScope.RuYiDbContext.DbMaintenance.GetTableInfoList();
                    }
                    catch
                    {
                        var sqlScriptPath = Path.Join(Directory.GetCurrentDirectory(), "/", RuYiGlobalConfig.DBConfig.SqlScriptPath);//Sql脚本路径
                        var content = File.ReadAllText(sqlScriptPath);//读取脚本内容
                        RuYiAdminDbScope.RuYiDbContext.DbMaintenance.CreateDatabase();//创建数据库
                        await RuYiAdminDbScope.RuYiDbContext.Ado.ExecuteCommandAsync(content); //构建表结构
                    }

                }
            });
        }

        #endregion

        #region 初始化多租户

        /// <summary>
        /// 初始化多租户
        /// </summary>
        /// <returns></returns>
        public static async Task InitTenants()
        {
            await Task.Run(() =>
            {
                var tenants = RuYiGlobalConfig.TenantsConfig.TenantsList;
                if (tenants.Count > 0)
                {
                    var connectionConfigs = new List<ConnectionConfig>();
                    foreach (var item in tenants)
                    {
                        var onnectionConfig = new ConnectionConfig()
                        {
                            ConfigId = item.TenantId,
                            DbType = (DbType)item.DbType,
                            ConnectionString = item.ConnectionString,
                            IsAutoCloseConnection = item.IsAutoCloseConnection,
                        };
                        connectionConfigs.Add(onnectionConfig);
                    }

                    RuYiAdminDbScope.RuYiTenantDbContext = new SqlSugarScope(connectionConfigs);

                    foreach (var item in tenants)
                    {
                        RuYiAdminDbScope.RuYiTenantDbContext.GetConnectionScope(item.TenantId).Aop.OnLogExecuting = (sql, p) =>
                        {
                            Console.WriteLine(sql);
                        };
                    }
                }
            });
        }

        #endregion
    }
}
